package com.vr.cloudpicture.manager.websocket.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.vr.cloudpicture.manager.websocket.model.PictureEditRequestMessage;
import com.vr.cloudpicture.manager.websocket.model.PictureEditResponseMessage;
import com.vr.cloudpicture.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import com.vr.cloudpicture.manager.websocket.strategy.PictureEditMessageStrategy;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import com.vr.cloudpicture.model.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * 图片编辑失败处理的策略
 *
 * @author hzh
 * @date 2025/05/28
 */
@Component
public class ErrorMessageStrategy implements PictureEditMessageStrategy {
    @Override
    public void handle(PictureEditRequestMessage requestMessage, WebSocketSession session, UserLogin user, Long pictureId) throws Exception {
        PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
        responseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
        responseMessage.setMessage("消息类型错误");
        responseMessage.setUser(BeanUtil.toBean(user, UserVO.class));
        // 创建序列化器，将Long类型转化成String类型，避免精度丢失
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(
                new SimpleModule()
                        .addSerializer(Long.class, ToStringSerializer.instance)
                        // 支持Long的基本类型
                        .addSerializer(Long.TYPE, ToStringSerializer.instance)
        );
        String message = objectMapper.writeValueAsString(responseMessage);
        TextMessage textMessage = new TextMessage(message);
        session.sendMessage(textMessage);
    }
}
